package com.sgcc.pda.hw.impl;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.sgcc.pda.hw.IProtocol376Manager;
import com.sgcc.pda.tools.LogPrintUtils;


/**
 * @创建者：suven on 2020/3/26 10:32
 * @描述：376.1协议操作方法
 * @版本：1.0
 * @修改人：
 * @修改时间：
 * @修改说明：
 * @修改版本：
 */
public class Protocol376Manager {

    private static final String PACKAGE_NAME = "com.sgcc.pda.hw";
    private static final String CLASS_NAME = "com.sgcc.pda.hw.AIDL_PROTOCOL_376_SERVICE";

    private static Protocol376Manager mInstance;
    private IProtocol376Manager mProtocol376Manager = null;
    private boolean bindflag = false;//绑定标志

    /**
     * 单例
     * @return
     */
    public static synchronized Protocol376Manager getInstance(){
        if(mInstance == null){
            mInstance = new Protocol376Manager();
        }
        return mInstance;
    }

    public IProtocol376Manager getProtocol376Manager(){
        return mProtocol376Manager;
    }

    public boolean isBind() {
        return bindflag;
    }
    public boolean bind(Context context){
        //如果没有绑定 则先进行aidl服务绑定
        if(!bindflag){
            Intent intent = new Intent(CLASS_NAME);
            intent.setPackage(PACKAGE_NAME);
            try {
                bindflag = context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
            } catch (SecurityException e) {
                e.printStackTrace();
                LogPrintUtils.d("IProtocol376Manager-绑定异常 ", e);
            }
        }
        return bindflag;
    }

    /**
     * 取消aidl绑定
     * @param context
     */
    public void unBind(Context context) {
        if (bindflag) context.unbindService(conn);
    }

    /**
     * 实例化aidl连接服务
     */
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogPrintUtils.d("绑定成功-IProtocol376Manager");
            bindflag = true;
            mProtocol376Manager = IProtocol376Manager.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogPrintUtils.d("解绑成功-IProtocol376Manager");
            mProtocol376Manager = null;
            bindflag = false;
        }
    };
}
